package com.example.app.manager.resdown

import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.LogUtils
import com.example.app.global.GlobalConstant
import com.libcommon.GlobalPath
import com.libcommon.ext.getDESDecrypt
import com.libcommon.ext.getFileMD5Name
import com.libcommon.ext.safeGetAppCompatActivity
import com.libhttp.HttpManager
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.atomic.AtomicInteger

/**
 * CreateBy:Joker
 * CreateTime:2024/1/26 0:05
 * description：礼物资源下载器
 */

object BaseResDownloadManager {

    private const val TAG = "BaseResDownloadManager"

    //记录并发下载数
    private var downSize = AtomicInteger(0)

    private val linkedBlockingQueue by lazy { LinkedBlockingQueue<BaseResEntity>() }

    /**
     * 预加礼物载资源
     */
    fun preDownloadRes(resEntity: BaseResEntity) {
        if (resEntity.mp4Url.isNullOrEmpty() && resEntity.svgaUrl.isNullOrEmpty()) return

        linkedBlockingQueue.offer(resEntity)
        handleNextQueue()
    }

    private fun handleNextQueue() {
        if (linkedBlockingQueue.isEmpty()) {
            downSize.getAndSet(0)
            return
        }

        if (downSize.get() > GlobalConstant.getDownloadSize()) {
            return
        }

        val res = linkedBlockingQueue.poll()
        if (res == null) {
            handleNextQueue()
            return
        }

        val svgaUrl = res.svgaUrl?.getDESDecrypt()
        val vapUrl = res.mp4Url?.getDESDecrypt()

        //预加载进房资源动画视频
        when {
            !vapUrl.isNullOrEmpty() -> {
                downLoadFileRes(vapUrl, getResMp4FilePath(vapUrl))             //vap
            }

            !svgaUrl.isNullOrEmpty() -> {
                downLoadFileRes(svgaUrl, getResSVGAFilePath(svgaUrl))          //svga
            }
        }
    }

    /**
     * 下载资源
     */
    private fun downLoadFileRes(url: String?, filePath: String) {
        if (url.isNullOrEmpty() || FileUtils.isFileExists(filePath)) {
            //不符合要求直接下一个
            handleNextQueue()
            return
        }

        safeGetAppCompatActivity()?.let {
            downSize.incrementAndGet()
            HttpManager.downloadFile(it, url, filePath, reqResult = { code, _, msg ->
                if (code == HttpManager.CODE_SUCCESS) {
                    LogUtils.dTag(TAG, "下载结果,code=$code,msg=$msg url=$url")
                } else {
                    LogUtils.eTag(TAG, "下载结果,code=$code,msg=$msg url=$url")
                }

                downSize.decrementAndGet()
                handleNextQueue()
            })
        }
    }

    fun getResSVGAFilePath(url: String?) = "${GlobalPath.getSvgaResPath()}/${url?.getDESDecrypt()?.getFileMD5Name()}"
    fun getResMp4FilePath(url: String?) = "${GlobalPath.getMp4ResPath()}/${url?.getDESDecrypt()?.getFileMD5Name()}"
}